package com.cctc.rds.nrpc.core.client.connection;

import com.cctc.rds.nrpc.api.connection.Connection;
import com.cctc.rds.nrpc.api.connection.client.ClientConnectionListener;
import com.cctc.rds.nrpc.api.connection.client.ClientConnectionListenerProvider;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.net.InetSocketAddress;
import java.util.List;

public class ClientConnection implements Connection {
    private Channel channel;
    private String remoteIp;
    private int remotePort;
    private int remotePid;

    public ClientConnection(Channel channel) {
        this.channel = channel;
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        this.remoteIp = socketAddress.getAddress().getHostAddress();
        this.remotePort = socketAddress.getPort();
        List<ClientConnectionListener> listeners = ClientConnectionListenerProvider.getInstance().list();
        if (listeners != null && listeners.size() > 0) {
            listeners.stream().forEach(listener -> listener.onSuccess(this));
        }
    }

    public Channel getChannel() {
        return channel;
    }

    @Override
    public String getConnectionKey() {
        return remoteIp + ":" + remotePort;
    }

    @Override
    public String getRemoteIp() {
        return remoteIp;
    }

    @Override
    public int getRemotePort() {
        return remotePort;
    }

    @Override
    public int getRemotePid() {
        if (remotePid == 0) {
            Object pid = channel.attr(AttributeKey.valueOf("PID")).get();
            remotePid = pid == null ? -1 : (int) pid;
        }
        return remotePid;
    }

    @Override
    public void close() throws Exception {
        if (channel != null && channel.isActive()) {
            channel.close();
            List<ClientConnectionListener> listeners = ClientConnectionListenerProvider.getInstance().list();
            if (listeners != null && listeners.size() > 0) {
                listeners.stream().forEach(listener -> listener.onClose(this));
            }
        }
    }
}
